package com.example.anpnovel.controller.crud;


import com.example.anpapi.entity.po.novelmodel.Novel.Novel;
import com.example.anpapi.entity.vo.R;
import com.example.anpnovel.service.interfaces.NovelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/novel")
public class NovelController {

    @Autowired
    private NovelService novelService;

    /**
     * 作品添加
     * @param novel
     * @return
     */
    @PostMapping("/save")
    public R<Novel> save(@RequestBody Novel novel){
        log.info("作品添加:{}", novel);
        novelService.save(novel);
        return R.success(novel,"作品添加成功");
    }

    /**
     * 根据作品id删除作品
     * @param novel
     * @return
     */
    @DeleteMapping("/remove")
    public R<String> remove(@RequestBody Novel novel){
        log.info("作品删除:{}", novel);
        if(novelService.getById(novel.getId()) != null)
        {
            novelService.removeById(novel.getId());
            return R.success(null,"作品删除成功");
        }
        return R.error("未找到该作品");
    }

    /**
     * 根据作品id查找作品
     * @param id
     * @return
     */
    @GetMapping("/get")
    public R<Novel> get(@RequestParam(value = "id") Long id) {
        log.info("查询作品的id为{}", id);
        Novel novel = novelService.getById(id);
        return R.success(novel, "查询作品成功");
    }

    /**
     * 根据作者id查找所有作品
     * @param authorId
     * @return
     */
    @GetMapping("/getByAuthorId")
    public R<List<Novel>> getByAuthorId(@RequestParam(value = "authorId") Long authorId) {
        log.info("查询作者id为{}的所有作品", authorId);
        List<Novel> novels = novelService.lambdaQuery()
                .eq(Novel::getAuthorId, authorId)
                .orderByDesc(Novel::getUpdatedTime)
                .list();
        return R.success(novels, "查询作品成功");
    }

    /**
     * 根据分类id查找所有作品
     * @param categoryId
     * @return
     */
    @GetMapping("/getByCategoryId")
    public R<List<Novel>> getByCategoryId(@RequestParam(value = "categoryId") Long categoryId) {
        log.info("查询分类id为{}的所有作品", categoryId);
        List<Novel> novels = novelService.lambdaQuery()
                .eq(Novel::getCategoryId, categoryId)
                .orderByDesc(Novel::getUpdatedTime)
                .list();
        return R.success(novels, "查询作品成功");
    }

    /**
     * 修改作品
     * @param novel
     * @return
     */
    @PostMapping("/update")
    public R<Novel> update(@RequestBody Novel novel){
        log.info("修改的作品为{}", novel);
        novelService.updateById(novel);
        return R.success(novel,"修改作品成功");
    }

}

